﻿//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//----------------------------------------------------------------

using System.Runtime.Serialization;
using System.Text;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using TTS;
using System;
using System.Collections.Generic;

namespace Microsoft.Samples.Jsonp
{
    [DataContract]
    public class AudioData
    {     
        [DataMember]
        public string audioBytes;
    }


    [DataContract]
    public class WebPageData
    {
        [DataMember]
        public string content;
    }


    [DataContract]
    public class RecognitionData
    {
        [DataMember]
        //Khi dữ liệu từ client gửi đi lớn, chỉ request cho block cuối cùng mới nhận kết quả finalResult là true
        public bool finalResult;

        [DataMember]
        public string text;
    }

    public class RecognitionStreamingData
    {
        class Data 
        {
            public int length;
            private string[] str;
            public Data(int length)
            {
                this.length = length;
                str = new string[length];
            }
            public void receive(int blockIndex, string base64)
            {
                length--;
                str[blockIndex] = base64;
            }
            public bool receiveAll(){
                return length == 0;
            }
            public string recognize()
            {
                StringBuilder builder = new StringBuilder();
                foreach (string value in str)
                {
                    builder.Append(value);
                }

                return TTSManager.recognize(Convert.FromBase64String(builder.ToString()));
            }
        }
        private Dictionary<string, Data> streamingRecognitionRequest;

        public RecognitionStreamingData()
        {
            streamingRecognitionRequest = new Dictionary<string, Data>();
        }

        public RecognitionData getRecognitionData(string ID, int length, int blockIndex, string base64)
        {
            if (!streamingRecognitionRequest.ContainsKey(ID))
                streamingRecognitionRequest.Add(ID, new Data(length));

            streamingRecognitionRequest[ID].receive(blockIndex, base64);

            if (streamingRecognitionRequest[ID].receiveAll())
            {
                string text = streamingRecognitionRequest[ID].recognize();
                streamingRecognitionRequest.Remove(ID);
                return new RecognitionData { finalResult = true, text = text };
            }
            else
                return new RecognitionData { finalResult = false, text = streamingRecognitionRequest[ID].length.ToString() }; ;
            
        }
    }

    [ServiceContract(Namespace = "JsonpAjaxService", SessionMode = SessionMode.Allowed)]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class TTSService
    {
        static RecognitionStreamingData stream = new RecognitionStreamingData();

        [WebGet(ResponseFormat = WebMessageFormat.Json)]
        public AudioData GetAudioData(string voiceIndex, string extension, string text)
        {
            if (extension == null || !extension.Equals(TextToSpeech.MP3))
                extension = TextToSpeech.WAV;
            TextToSpeech tts = TTSManager.getTextToSpeech(voiceIndex);
            byte[] b = tts.getAudioBytes(text, extension);
            return new AudioData() { audioBytes = Convert.ToBase64String(b)};
        }

        [WebGet(ResponseFormat = WebMessageFormat.Json)]
        public WebPageData GetWebPageData(string url)
        {
            WebClient w = new WebClient();
            w.Encoding = Encoding.UTF8;
            string html;
            try
            {
                string _htmldoc = w.DownloadString(@url);
                HTMLMarkerClass.DOM _dom = new HTMLMarkerClass.DOM();
                html = _dom.getMainContent(_htmldoc);
            }
            catch (Exception ex)
            {
                html = "<HTML><HEAD><meta http-equiv='Content-Type' content='text/html; charset=utf-8' /></HEAD><BODY></br><P>Không tải được trang Web yêu cầu</P></BODY></HTML>";
            }
            
            return new WebPageData() { content = html };
        }


        [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
        public RecognitionData GetRecognitionData(string ID, int length, int blockIndex, string base64)
        {
            lock (stream)
            {
                return stream.getRecognitionData(ID, length, blockIndex, base64);
            }
        }
    }
}
